import { createRouter, createWebHistory } from "vue-router";
import { start, close } from "@/utils/nprogressUtils"
import { useHomeStore } from '@/stores/index'
import { findTreeMenu } from '@/apis/index'


const routes = [
    {
        path: "/",
        name: "layout",
        component: () => import("@/views/Index.vue"),
        redirect: "/login",
        children: [
            {
                path: "index",
                name: "index",
                component: () => import("@/views/index/Index.vue")
            }
        ]
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/Login.vue") // 动态导入组件
    }
]; // 路由匹配规则
const history = createWebHistory(); // 路由模式
const router = createRouter({
    history,
    routes,
}) // 创建路由实例

router.beforeEach(async (to, from, next) => {
    start() // 开启进度条
    const store = useHomeStore()
    // 如果登录状态，并且还是登录页面，就重定向到首页
    if (store.isLogin && to.path === '/login') {
        next({ path: '/index' })
        return
    }
    // 如果没有登录，并且要访问登录页面，就放行
    if (to.path === '/login' && !store.isLogin) {
        next()
        return
    }
    // 如果已经登录，就获取路由信息，并放行
    if (store.isLogin && store.menuTree.length <= 0) {
        store.menuTree = await findTreeMenu()
        console.log(store.menuTree)
        store.addRouters() // 动态添加路由
        next({ ...to, replace: true }) // 重定向到当前路由，避免刷新页面后，路由丢失
        return
    }
    next()
})

router.afterEach(() => {
    close() // 关闭进度条
})



export default router; // 导出路由实例

